﻿using System;
using System.Linq;
using System.Collections.Generic;

namespace Translator
{
    public class BingProvider : ITranslationProvider
    {
        readonly static Dictionary<string, string> languages = new Dictionary<string, string>() { 
            { "English", "En" },    
            { "German", "De" },
            { "Spanish", "Es" },
            { "French", "Fr" },
            { "Italian", "It" },
            { "Arabic", "Ar" }, 
            { "Japanese", "Ja" },
            { "Korean", "Ko" },
            { "Dutch", "Nl" },
            { "Polish", "Pl" },
            { "Portuguese", "Pt" },
            { "Russian", "Ru" },
            { "Simplified Chinese", "zh-CHS" },
            { "Traditional Chinese", "zh-CHT" }
        };
         
        public bool Translate(string word, string sourceLang, string targetLang, out List<Term> terms, out string error)
        {
            terms = new List<Term>();
            error = null;

            using (BingService.BingService service = new BingService.BingService())
            {
                try
                {
                    BingService.SearchRequest request = new BingService.SearchRequest();
                    request.Version = "2.2";
                    request.AppId = "9E9998AE3C8C0C2033ABA50DD958E1953A3AF3DD";
                    request.Query = word;
                    request.Sources = new BingService.SourceType[] { BingService.SourceType.Translation };
                    request.Translation = new BingService.TranslationRequest() { SourceLanguage = languages[sourceLang], TargetLanguage = languages[targetLang] };
                    BingService.SearchResponse response = service.Search(request);
                    if (response != null && response.Translation != null && response.Translation.Results != null)
                    {
                        foreach (var result in response.Translation.Results) 
                            terms.Add(new Term() { Lang1 = word, Lang2 = result.TranslatedTerm });
                        return true;
                    }
                    return false;
                }
                catch (System.Web.Services.Protocols.SoapException ex)
                {
                    error = ex.Detail.InnerText;
                }
                catch (Exception ex)
                {
                    error = ex.Message;
                }
                return false;
            }
        }

        public string[] SourceLanguages { get { return languages.Keys.ToArray(); } }
        public string[] TargetLanguages { get { return SourceLanguages; } }
    }
}
